<?php
class register
{
	public function defaultaction()
	{
		echo view::show('register/form', lib::getitem('POST', lib::NO_PERSISTENT_STORAGE));
	}
	
	public function process()
	{
		lib::setitem('POST', $_POST);
		
		if(!lib::checkseccode($_POST['seccode'])){
			lib::seterror(lang::WRONG_SECCODE);
			lib::sendto('/register');
		}
		
		$username = $_POST['username'];
		$password = $_POST['password'];
		$email = $_POST['email'];
		
		if(empty($username) || !lib::checkusername($username)){
			lib::seterror(lang::REQUIRE_USERNAME);
			lib::sendto('/register');
		}
		
		if(empty($password)){
			lib::seterror(lang::REQUIRE_PASSWORD);
			lib::sendto('/register');
		}
		
		if(empty($email) || !lib::checkemail($email)){
			lib::seterror(lang::REQUIRE_EMAIL);
			lib::sendto('/register');
		}
		
		if(lib::isuserexist($username)){
			lib::seterror(lang::AN_EXIST_USER);
			lib::sendto('/register');
		}
		
		$user = new user();
		$user->username = htmlspecialchars($username);
		$user->password = lib::makehashedpassword($user,$password);
		$user->email = $email;
		$user->save();
		
		lib::setitem('username', $username);
		lib::setmessage(lang::REGISTERED);
		lib::sendto('/login');
		
	}
	
	public function valid(){
		$controller = lib::getitem('controller');
		$username = $controller->params[0];
		if(lib::isuserexist($username)){
			$jsonstr = '{"code":0}';		
		}else{
			$jsonstr = '{"code":1}';
		}		 
		die($jsonstr);
	}
}